package com.llws.petgoodsshop.controller;


import com.llws.petgoodsshop.bean.RtnInfo;
import com.llws.petgoodsshop.bean.Users;
import com.llws.petgoodsshop.bean.UsersVo;
import com.llws.petgoodsshop.mapper.UsersMapper;
import com.llws.petgoodsshop.utils.CpachaUtil;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UsersMapper usersMapper;
    /**
     * 生成验证码图片
     * 请求方式:GET
     * 请求url: /pet/user/verifyCode
     * 返回结果: JSON字符串
     * @param tokenStr
     * @param request
     * @param resp
     * @throws IOException
     */
    @RequestMapping(value="verifyCode" ,method = RequestMethod.GET)
    public void verifyCode(String tokenStr, HttpServletRequest request, HttpServletResponse resp) throws IOException {
        CpachaUtil cpachaUtil = new CpachaUtil(4,100,30);//指定验证码长度、图片宽度、高度
        //生成随机的验证码(四个字符的字符串)
        String generatorVCode = cpachaUtil.generatorVCode();
        //将验证码保存到session
        HttpSession session = request.getSession();
        //设置超时
        //session.setMaxInactiveInterval(60);//以秒为单位
        //将验证码存放到session，主要是在登录的servlet中实现跟前台的验证码进行匹配
        session.setAttribute("vCode",generatorVCode);// aaa   bbb
        System.out.println("-----------------保存session:"+session.getId()+" "+generatorVCode);
        //生成一个验证码图片，响应到前台
        BufferedImage g = cpachaUtil.generatorRotateVCodeImage(generatorVCode,true);
        //回写
        ImageIO.write(g,"gif",resp.getOutputStream());
    }

    /**
     * 登录
     * 请求方式:POST
     * 请求url: /bookshop/user/login
     * 返回结果: JSON字符串
     *
     * A:保存session:80ADEEA96A204E7BFCF96CE4AAFCD934 nDaJ
     * A:获取session:80ADEEA96A204E7BFCF96CE4AAFCD934 nDaJ
     *
     * B:保存session:AC22B1100F25A629C5EB7FD1BC6C8D6D aA5w
     * B:获取session:AC22B1100F25A629C5EB7FD1BC6C8D6D aA5w
     * @param request
     * @param users
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public RtnInfo login(HttpServletRequest request, UsersVo users) throws Exception {
        System.out.println("进入到了登录后台：\n"+users);
        // 创建一个RtnInfo对象，存放响应到前端的信息
        RtnInfo rtnInfo = new RtnInfo();
        // 对传过来的数据进行非空校验
        if(StringUtils.isNullOrEmpty(users.getPhone())){
            rtnInfo.setCode(-1);
            rtnInfo.setMsg("手机号不能为空！");
        }else if(StringUtils.isNullOrEmpty(users.getPassword())){
            rtnInfo.setCode(-1);
            rtnInfo.setMsg("密码不能为空！");
        }else if(StringUtils.isNullOrEmpty(users.getVcode())){
            rtnInfo.setCode(-1);
            rtnInfo.setMsg("验证码不能为空！");
        }else{
            // 获取session中存储的验证码
            HttpSession session = request.getSession();
            String vcode = (String) session.getAttribute("vCode");
            System.out.println("-----------------获取session:"+session.getId()+" "+vcode);
            // 校验验证码（判断前端传过来的验证码和服务器上的验证码是否一致）
            if(vcode==null || !vcode.equalsIgnoreCase(users.getVcode())){ // ABC = abc
                rtnInfo.setCode(-1);
                rtnInfo.setMsg("验证码输入错误！");
            }else{// 验证码通过，通过数据库校验phone，password是否正确
                Users query = usersMapper.login(users);
                if(query!=null){
                    rtnInfo.setCode(1);
                    rtnInfo.setMsg("用户登录成功！");
                    rtnInfo.setResult(query);
                    session.setAttribute("user",query);
                }else{
                    rtnInfo.setCode(0);
                    rtnInfo.setMsg("用户登录失败！");
                }
            }
        }
        return rtnInfo;// springboot会自动转成json字符串响应到前端
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public RtnInfo update(Users users) throws Exception {
        RtnInfo rtnInfo = new RtnInfo();
        // 创建一个RtnInfo对象，存放响应到前端的信息
        // 对传过来的数据进行非空校验
        if(StringUtils.isNullOrEmpty(users.getNickname())){
            rtnInfo.setCode(-1);
            rtnInfo.setMsg("昵称不能为空！");
        }else if(StringUtils.isNullOrEmpty(users.getAddress())) {
            rtnInfo.setCode(-1);
            rtnInfo.setMsg("地址不能为空！");
        }else{
            int count = usersMapper.update(users);
            if(count>0){
                rtnInfo.setCode(1);
                rtnInfo.setMsg("用户信息更新成功！");
                Users query = usersMapper.findUsersById(users.getUserId());
                query.setPassword("");
                rtnInfo.setResult(query);
            }else{
                rtnInfo.setCode(0);
                rtnInfo.setMsg("用户信息更新失败！");
            }
        }
        return rtnInfo;
    }

    @RequestMapping(value = "updatePwd", method = RequestMethod.POST)
    public RtnInfo updatePwd(HttpSession session, @RequestParam("oldPassword")String oldPassword, @RequestParam("newPassword") String newPassword) throws Exception {
        RtnInfo rtnInfo = new RtnInfo();
        // 创建一个RtnInfo对象，存放响应到前端的信息
        // 对传过来的数据进行非空校验
        if(StringUtils.isNullOrEmpty(oldPassword)){
            rtnInfo.setCode(-1);
            rtnInfo.setMsg("旧密码不能为空！");
        }else if(StringUtils.isNullOrEmpty(newPassword)) {
            rtnInfo.setCode(-1);
            rtnInfo.setMsg("新密码不能为空！");
        }else{
            Users users= (Users) session.getAttribute("user");
            if (!users.getPassword().equals(oldPassword)) {
                rtnInfo.setCode(-1);
                rtnInfo.setMsg("旧密码错误！");
            }else {
                users.setPassword(newPassword);
                int count = usersMapper.update(users);
                if (count>0){
                    rtnInfo.setCode(1);
                    rtnInfo.setMsg("密码更新成功！");
                }
            }

        }
        return rtnInfo;
    }
}
